package com.ph.controller.personal.account;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ph.constant.PsResultEnum;
import com.ph.custom.annotation.MemberCache;
import com.ph.custom.annotation.Token;
import com.ph.custom.cenum.UserCacheEnum;
import com.ph.entity.MemberInfo;
import com.ph.shopping.common.core.customenum.MemberEnum;
import com.ph.shopping.common.core.customenum.ResultEnum;
import com.ph.shopping.common.util.result.Result;
import com.ph.shopping.facade.member.dto.CertificatesAuthDto;
import com.ph.shopping.facade.member.dto.MemberPasswordDto;
import com.ph.shopping.facade.member.dto.PayPasswordDto;
import com.ph.shopping.facade.member.entity.Member;
import com.ph.shopping.facade.member.entity.TradersPassword;
import com.ph.shopping.facade.member.service.ICretificateAuthService;
import com.ph.shopping.facade.member.service.IMemberService;
import com.ph.shopping.facade.member.vo.MemberPhoneUpdataVo;
import com.ph.shopping.facade.member.vo.PasswordVo;
import com.ph.spenum.PromptEnum;
import com.ph.util.ResultUtil;
/**
 * 
 * @ClassName:  AccountSecurityController   
 * @Description: 个人安全相关action
 * @author: lijie
 * @date:   2017年4月17日 上午10:03:05     
 * @Copyright: 2017
 */
@Controller
@RequestMapping("account")
public class AccountSecurityController {

	private static final Logger logger = LoggerFactory.getLogger(AccountSecurityController.class);
	
	@Reference(version = "1.0.0", retries = 0, timeout = 30000)
	private IMemberService memberService;
	
	@Reference(version = "1.0.0", retries = 0, timeout = 30000)
	private ICretificateAuthService cretificateAuthService;
	/**
	 * 
	* @Title: loadAccountSecurity  
	* @Description: 加载账户安全页面
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	@MemberCache
	@RequestMapping(value = "/loadAccountSecurity", method = RequestMethod.GET)
	public String loadAccountSecurity(HttpServletRequest request, Model model,MemberInfo memberInfo) {
		try {
			if (memberInfo != null) {
				String mobile = memberInfo.getMemberPhone();
				Result paypwd = memberService.getMemberPayPwdInfoByMobile(mobile);
				Result result = memberService.getMemberInfoByMobile(mobile);
				if (result != null && ResultEnum.SUCCESS.getCode().equals(result.getCode())) {
					model.addAttribute("member", result.getData());
				}
				if (paypwd != null && ResultEnum.SUCCESS.getCode().equals(paypwd.getCode())) {
					model.addAttribute("paypwd", paypwd.getData());
				}
			}
		} catch (Exception e) {
			logger.error("加载账户安全页面错误", e);
		}
		return "account/accountSecurity";
	}
	/**
	 * 
	* @Title: loadlogin  
	* @Description: 加载修改手机号页面  
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	@MemberCache
	@RequestMapping(value = "/loadUpdatePhone", method = RequestMethod.GET)
	public String loadUpdatePhone(HttpServletRequest request, Model model) {
		
		return "account/updatePhone";
	}
	/**
	 * 
	* @Title: loadAuthDetail  
	* @Description: 加载认证详情页面  
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	@MemberCache
	@RequestMapping(value = "/loadAuthDetail", method = RequestMethod.GET)
	public String loadAuthDetail(HttpServletRequest request, Model model,MemberInfo memberInfo) {
		try {
			if (memberInfo != null ) {
				Result result = cretificateAuthService.getCretificateAuthInfo(memberInfo.getIdCard());
				if(result != null && ResultEnum.SUCCESS.getCode().equals(result.getCode())){
					model.addAttribute("cerAuth",result.getData());
				}
			} 
		} catch (Exception e) {
			logger.error("加载认证详情页面   错误", e);
		}
		return "account/authDetail";
	}
	/**
	 * 
	* @Title: loadRealNameAuth  
	* @Description: 加载实名认证页面  
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	@MemberCache
	@RequestMapping(value = "/loadRealNameAuth", method = RequestMethod.GET)
	public String loadRealNameAuth(HttpServletRequest request, Model model) {
		return "account/realNameAuth";
	}
	/**
	 * 
	* @Title: loadUpdateLoginPwd  
	* @Description: 加载修改登录密码页面
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	@MemberCache
	@RequestMapping(value = "/loadUpdateLoginPwd", method = RequestMethod.GET)
	public String loadUpdateLoginPwd(HttpServletRequest request, Model model) {
		return "account/updateLoginPwd";
	}
	/**
	 * 
	* @Title: loadUpdatePayPwd  
	* @Description: 加载修改支付密码页面  
	* @param @return    参数  
	* @return String    返回类型  
	* @throws
	 */
	@MemberCache
	@RequestMapping(value = "/loadUpdatePayPwd", method = RequestMethod.GET)
	public String loadUpdatePayPwd(HttpServletRequest request, Model model) {
		return "account/updatePayPwd";
	}
	/**
	 * 
	 * @Title: loadSetUpPayPwd   
	 * @Description: 加载设置支付密码页面啊
	 * @param: @param request
	 * @param: @param model
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@MemberCache
	@RequestMapping(value = "/loadSetUpPayPwd", method = RequestMethod.GET)
	public String loadSetUpPayPwd(HttpServletRequest request, Model model) {
		return "account/setUpPayPwd";
	}
	/**
	 * 
	 * @Title: commonPrompt   
	 * @Description: 加载统一成功提示页面   
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	@MemberCache
	@RequestMapping(value = "/commonPrompt", method = RequestMethod.GET)
	public String commonPrompt(HttpServletRequest request, Model model,String pCode) {
		model.addAttribute("message", PromptEnum.getMessageByCode(pCode));
		model.addAttribute("pCode", pCode);
		return "account/commonPrompt";
	}
	/**
	 * 
	* @Title: backPwdSubmit  
	* @Description: 修改手机号  
	* @param @param request
	* @param @param vo
	* @param @return    参数  
	* @return Map<String,Object>    返回类型  
	* @throws
	 */
	@ResponseBody
	@Token(errorDesc = "验证码超时")
	@RequestMapping("/updatePhoneSubmit")
	@MemberCache(userCache = { UserCacheEnum.UPDATE })
	public Map<String, Object> backPwdSubmit(HttpServletRequest request, MemberInfo memberInfo,MemberPhoneUpdataVo vo) {
		logger.info("修改手机号处理参数：MemberPhoneUpdataVo = {} ", JSON.toJSONString(vo));
		Map<String, Object> map = ResultUtil.setResult(false, PsResultEnum.FAIL.getMsg());
		try {
			Result result = memberService.updateMemberPhone(vo);
			logger.info("修改手机号处理返回数据：Result = {} ", JSON.toJSONString(result));
			if (result != null) {
				String code = result.getCode();
				if (ResultEnum.SUCCESS.getCode().equals(code)) {
					ResultUtil.setResult(map, true, "修改手机号成功");
					MemberInfo newmember = getMemberInfoByMobile(vo.getNewPhone());
					if(newmember != null){
						BeanUtils.copyProperties(newmember, memberInfo);
					}
				} else if (ResultEnum.MEMBER_NATIVE_PWD_MISMATCH.getCode().equals(code)) {
					ResultUtil.setResult(map, false, "支付密码错误");
				}
			}
		} catch (Exception e) {
			logger.error("修改手机号处理错误", e);
			ResultUtil.setResult(map, false, "服务器繁忙请稍后再试");
		}
		return map;
	}
	/**
	 * 
	 * @Title: updatePwdSubmit   
	 * @Description: 修改登录密码   
	 * @param: @param request
	 * @param: @param dto
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@ResponseBody
	@Token(errorDesc = "验证码超时")
	@RequestMapping("/updatePwdSubmit")
	public Map<String, Object> updatePwdSubmit(HttpServletRequest request, PasswordVo vo) {
		logger.info("修改登录密码处理参数：PasswordVo = {} ", JSON.toJSONString(vo));
		Map<String, Object> map = ResultUtil.setResult(false, PsResultEnum.FAIL.getMsg());
		try {
			if (vo != null) {
				MemberPasswordDto dto = new MemberPasswordDto();
				dto.setMemberPhone(vo.getPhone());
				dto.setNewPassword(vo.getNewPwd());
				Result result = memberService.updateMemberPassword(dto);
				logger.info("修改登录密码处理返回数据：Result = {} ", JSON.toJSONString(result));
				if (result != null) {
					String code = result.getCode();
					if (ResultEnum.SUCCESS.getCode().equals(code)) {
						ResultUtil.setResult(map, true, "修改登录成功");
					}
				}
			}
		} catch (Exception e) {
			logger.error("修改登录密码处理错误", e);
			ResultUtil.setResult(map, false, "服务器繁忙请稍后再试");
		}
		return map;
	}
	/**
	 * 
	 * @Title: updatePayPwdSubmit   
	 * @Description:修改支付密码  
	 * @param: @param request
	 * @param: @param dto
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@ResponseBody
	@MemberCache
	@Token(errorDesc = "验证码超时")
	@RequestMapping("/updatePayPwdSubmit")
	public Map<String, Object> updatePayPwdSubmit(HttpServletRequest request, MemberInfo memberInfo, PasswordVo vo) {
		logger.info("修改支付密码处理参数：PasswordVo = {} ", JSON.toJSONString(vo));
		Map<String, Object> map = ResultUtil.setResult(false, PsResultEnum.FAIL.getMsg());
		try {
			if (vo != null) {
				if (memberInfo == null || memberInfo.getId() == null) {
					logger.warn("修改会员支付密码未获取到相关用户信息");
				} else {
					PayPasswordDto dto = new PayPasswordDto();
					dto.setCustomerType(MemberEnum.MEMBER_PAY_PWD.getCode().intValue());
					dto.setNewPassword(vo.getNewPwd());
					dto.setRelatedId(memberInfo.getId());
					dto.setUpdateUser(memberInfo.getId());
					Result result = memberService.updatePayPassword(dto);
					logger.info("修改支付密码处理返回数据：Result = {} ", JSON.toJSONString(result));
					if (result != null) {
						String code = result.getCode();
						if (ResultEnum.SUCCESS.getCode().equals(code)) {
							ResultUtil.setResult(map, true, "修改支付密码成功");
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("修改支付密码处理错误", e);
			ResultUtil.setResult(map, false, "服务器繁忙请稍后再试");
		}
		return map;
	}
	
	/**
	 * 
	 * @Title: setUpPayPwdSubmit   
	 * @Description: 设置支付密码   
	 * @param: @param request
	 * @param: @param vo
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@ResponseBody
	@MemberCache
	@Token(errorDesc = "验证码超时")
	@RequestMapping("/setUpPayPwdSubmit")
	public Map<String, Object> setUpPayPwdSubmit(HttpServletRequest request, MemberInfo memberInfo, PasswordVo vo) {
		logger.info("设置支付密码处理参数：PasswordVo = {} ", JSON.toJSONString(vo));
		Map<String, Object> map = ResultUtil.setResult(false, PsResultEnum.FAIL.getMsg());
		try {
			if (vo != null) {
				if (memberInfo == null || memberInfo.getId() == null) {
					logger.warn("设置会员支付密码未获取相关用户信息");
				} else {
					TradersPassword tradersPassword = new TradersPassword();
					tradersPassword.setCustomerType(MemberEnum.MEMBER_PAY_PWD.getCode().intValue());
					tradersPassword.setPayPwd(vo.getNewPwd());
					tradersPassword.setRelatedId(memberInfo.getId());
					tradersPassword.setCreateUser(memberInfo.getId());
					Result result = memberService.addMemberPayPwd(tradersPassword);
					logger.info("设置支付密码处理返回数据：Result = {} ", JSON.toJSONString(result));
					if (result != null) {
						String code = result.getCode();
						if (ResultEnum.SUCCESS.getCode().equals(code)) {
							ResultUtil.setResult(map, true, "设置支付密码成功");
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("设置支付密码处理错误", e);
			ResultUtil.setResult(map, false, "服务器繁忙请稍后再试");
		}
		return map;
	}
	/**
	 * 
	 * @Title: realNameAuth   
	 * @Description: 身份证认证  
	 * @param: @param request
	 * @param: @param vo
	 * @param: @return      
	 * @return: Map<String,Object>      
	 * @throws
	 */
	@RequestMapping("/realNameAuth")
	@ResponseBody
	@MemberCache(userCache = { UserCacheEnum.UPDATE, UserCacheEnum.SELECT })
	public Map<String, Object> realNameAuth(HttpServletRequest request, MemberInfo memberInfo,
			CertificatesAuthDto dto) {
		logger.info("实名认证处理参数：PasswordVo = {} ", JSON.toJSONString(dto));
		Map<String, Object> map = ResultUtil.setResult(false, PsResultEnum.FAIL.getMsg());
		try {
			if (dto != null) {
				if (memberInfo == null || memberInfo.getId() == null) {
					logger.warn("实名认证未获取相关用户信息");
				} else {
					dto.setUserId(memberInfo.getId());
					MemberInfo newmember = null;
					Result result = cretificateAuthService.idCretificateAuth(dto);
					logger.info("实名认证返回数据：Result = {} ", JSON.toJSONString(result));
					if (result != null) {
						String code = result.getCode();
						if (ResultEnum.SUCCESS.getCode().equals(code)) {
							newmember = getMemberInfoByMobile(memberInfo.getMemberPhone());
							if (newmember != null) {
								BeanUtils.copyProperties(newmember, memberInfo);
							}
							ResultUtil.setResult(map, true, "实名认证成功");
						} else if (ResultEnum.MEMBER_DATA_EXISTS.getCode().equals(code)) {
							ResultUtil.setResult(map, false, "当前身份证已被认证");
						}
					}
				}
			}
		} catch (Exception e) {
			logger.error("实名认证处理错误", e);
			ResultUtil.setResult(map, false, "服务器繁忙请稍后再试");
		}
		return map;
	}
	/**
	 * 
	 * @Title: getMemberInfoByMobile   
	 * @Description: 根据手机号获取会员信息   
	 * @param: @param phone
	 * @param: @return      
	 * @return: MemberInfo      
	 * @throws
	 */
	private MemberInfo getMemberInfoByMobile(String phone){
		MemberInfo memberInfo = null;
		if(StringUtils.isNotBlank(phone)){
			Result result = memberService.getMemberInfoByMobile(phone);
			logger.info("根据手机号获取会员信息返回数据：Result = {} ", JSON.toJSONString(result));
			if (result != null) {
				if (ResultEnum.SUCCESS.getCode().equals(result.getCode())) {
					Object data = result.getData();
					if(data instanceof Member){
						memberInfo = new MemberInfo();
						BeanUtils.copyProperties(data, memberInfo);
					}
				}
			}
		}
		return memberInfo;
	}
}
